#!/usr/bin/env python
# -*- coding: utf-8 -*-

import Tkinter
import sys

from api import XinliFMApi
from model import SongList
from player import Player
from utils import get_songs_list_by_ids, format_time, time_past_percent
from downloader import Downloader


class Application(Tkinter.Frame):
    def __init__(self, master=None):
        Tkinter.Frame.__init__(self, master)

        self.__padx = 5
        self.__pady = 5

        self.columnconfigure(0, weight=5)

        self.grid(
            row=0, column=0, sticky='nswe', padx=self.__padx, pady=self.__pady)

        self.init()

    def init(self):
        self.api = XinliFMApi()
        self.downloader = Downloader()
        self.songList = SongList()
        self.musicPlayer = Player(self.downloader)
        self.songList.add_songs(
            get_songs_list_by_ids(self.api.get_latest_list()))
        self.current_song = self.songList.get_current_song()
        if not self.current_song:
            sys.exit()

        self.init_ui()

        self.start_play()

        self.tick()

    def init_ui(self):
        # self.cover = Tkinter.Label(self, bitmap='warning')
        # self.cover.grid(
        #     row=0, column=0, rowspan=3, columnspan=3, sticky='nesw')

        self.title_str = Tkinter.StringVar()
        self.title_str.set(self.current_song.title)
        self.title = Tkinter.Label(self, textvariable=self.title_str)
        self.title.grid(row=0, column=3, columnspan=6, sticky='w')

        self.speaker_str = Tkinter.StringVar()
        self.speaker_str.set(self.current_song.speak)
        self.speaker = Tkinter.Label(self, textvariable=self.speaker_str)
        self.speaker.grid(row=1, column=3, columnspan=3, sticky='w')

        self.timer_str = Tkinter.StringVar()
        self.timer_str.set('00:00 - 00:00')
        self.timer = Tkinter.Label(self, textvariable=self.timer_str)
        self.timer.grid(row=1, column=6, columnspan=3, sticky='e')

        self.progress_bar = Tkinter.Scale(
            self, orient=Tkinter.HORIZONTAL, length=200, showvalue=0)
        self.progress_bar.grid(row=2, column=3, columnspan=6, sticky='w')

        self.btn_toggle_str = Tkinter.StringVar()
        self.btn_toggle_str.set('Pause')
        self.btn_toggle = Tkinter.Button(
            self, textvariable=self.btn_toggle_str, command=self.play_toggle)
        self.btn_toggle.grid(row=3, column=3, columnspan=3, sticky='w')

        self.btn_favor = Tkinter.Button(self, text='Favor')
        self.btn_favor.grid(row=3, column=6)

        self.btn_trash = Tkinter.Button(self, text='Trash')
        self.btn_trash.grid(row=3, column=7)

        self.btn_skip = Tkinter.Button(
            self, text='Skip', command=self.play_next)
        self.btn_skip.grid(row=3, column=8)

    def update_ui(self):
        self.title_str.set(self.current_song.title)
        self.speaker_str.set(self.current_song.speak)

    def tick(self):
        self.update_timer()

    def start_play(self):
        self.musicPlayer.play(self.current_song)
        next_song = self.songList.get_next_song()
        self.downloader.add_task(next_song)

    def play_next(self):
        self.musicPlayer.stop()
        next_song = self.songList.get_next_song()
        self.songList.set_current_song(next_song.id)
        self.current_song = next_song

        self.update_ui()
        self.musicPlayer.play(self.current_song)

        next_song = self.songList.get_next_song()
        self.downloader.add_task(next_song)

    def play_toggle(self):
        self.musicPlayer.toggle()
        if self.musicPlayer.isplaying():
            self.btn_toggle_str.set("Pause")
        else:
            self.btn_toggle_str.set("Play ")

    def update_timer(self):
        time_string = '{} - {}'.format(
            format_time(self.musicPlayer.position()),
            format_time(self.musicPlayer.seconds()))
        self.timer_str.set(time_string)
        self.progress_bar.set(
            time_past_percent(self.musicPlayer.position(),
                              self.musicPlayer.seconds()))

        if self.musicPlayer.position() == self.musicPlayer.seconds():
            self.play_next()

        self.timer.after(500, self.update_timer)


if __name__ == '__main__':
    root = Tkinter.Tk()
    root.title('XinliFM - by wlemuel')
    root.resizable(0, 0)
    root.columnconfigure(0, weight=1)
    app = Application(root)
    # root.geometry('640x360')
    root.mainloop()
